const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
const cookieParser = require('cookie-parser');
const path = require('path');
const themesRouter = require('./routes/themesRouter');
const setupSocketHandlers = require('./utils/socketHandlers');

require('dotenv').config();

const app = express();

const PORT = process.env.PORT || 3000;

app.use(cors());
app.use(cookieParser());
app.use(morgan('dev'));
app.use(express.json());
app.use(express.static('public'));
app.use(express.static(path.join(__dirname, '..', 'dist')));

app.use('/api/themes', themesRouter);

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, '..', 'dist', 'index.html'));
});

const http = require('http');
const { Server } = require('socket.io');

const server = http.createServer(app);

const io = new Server(server, {
  cors: {
    origin: `https://${process.env.CUR_DOMAIN}`,
    methods: ['GET', 'POST'],
  },
});

setupSocketHandlers(io);

server.listen(PORT, () => console.log(`Started on port ${PORT}`));
